<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\Project;
use App\Models\AdminUser;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class DisPatchForm extends Form
{

    use LazyWidget;

    // 处理请求

    /**
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // 获取外部传递参数
        $row = $this->payload['row'] ?? null;
        $id = $row['id'];
        $model = \App\Models\Project::find($id);
        if (!$model) {
            return $this->response()->error('参数错误');
        }
        if ($model->status == 1 || $model->is_contract == 0) {
            return $this->response()->error('项目已完结, 或不允许签约');
        }
        $worker = AdminUser::whereIn('id', $input['worker_user_id'])
            ->select('name')
            ->pluck('name')
            ->toArray();
        $result = \App\Models\Project::where('id', $id)
            ->update([
                'worker_user_id' => implode(',', $input['worker_user_id']),
                'worker_user_name' => implode(' | ', $worker)
            ]);
        if ($result) {
            return $this->response()->success('成功')->refresh();
        } else {
            return $this->response()->error('失败');
        }
    }

    public function form()
    {
        // 分配的人
        $this->multipleSelect('worker_user_id', '请选择人员')->options(Project::getWorkerList());
    }

    public function
    default()
    {
        $row = $this->payload['row'] ?? null;
        return [
            'worker_user_id' => $row['worker_user_id']
        ];
    }
}
